<!--后结算--日清--收款 -->
<template>
  <div class="invoice-list-box">
    <el-container class="partDetails is-vertical">
      <el-header
        class="common-ui"
        height="auto">
        <record-info
          :record-form="nissinReadColunmns"
          :record-data="headerInfo" />
      </el-header>
      <div class="common-ui">
        <h3 style="padding: 8px;">收款记录</h3>
        <el-editable
          class="distributor-edit-box"
          :data="collectionList"
          height="300"
          v-loading="tableLoading"
          :columns="collectionColumns"
        />
      </div>
      <div class="common-ui">
        <h3 style="padding: 8px;">发票</h3>
        <el-editable
          ref="table"
          class="distributor-edit-box"
          :data="invoiceList"
          height="300"
          v-loading="tableLoading"
          @select="select"
          :columns="invoiceColumns"
        >
          <!-- 发票详情 -->
          <template
            slot="default-invoiceDetail"
            slot-scope="scope">
            <el-button
              @click="toLookDetailsList(scope.row)"
              type="text">查看</el-button>
          </template>
          <!-- 发票影像 -->
          <template
            slot="default-invoiceUrl"
            slot-scope="scope">
            <div
              v-if="scope.row.invoiceUrl"
              style="display:flex; justify-content: center;">
              <el-image
                @click="toLookDetails(scope.row)"
                style="width: 23px; height: 16.6px;"
                :src="imageicon"/>
            </div>
          </template>
        </el-editable>
      </div>
    </el-container>

    <el-dialog
      title="财务收款"
      :visible.sync="nissinVisble"
      width="550px"
      @close="handleClose">
      <el-form
        :model="receiptForm"
        label-width="100px">
        <el-form-item label="客户">
          <p>{{ headerInfo.hospitalName }}</p>
        </el-form-item>
        <div style="display:flex;">
          <el-form-item label="应收总金额">
            <p style="margin-right:100px;">{{ headerInfo.invoiceAmount }}</p>
          </el-form-item>
          <el-form-item label="剩余收款金额">
            <p>{{ surplusMoney ? surplusMoney.toFixed(3) : 0 }}</p>
          </el-form-item>
        </div>
        <div style="width:400px;">
          <el-form-item label="本次收款">
            <el-input-number
              :controls="false"
              :precision="3"
              v-model="receiptForm.tradeAmount"
              placeholder="请输入内容"/>
          </el-form-item>
          <el-form-item label="备注">
            <el-input
              type="textarea"
              :rows="3"
              :max-length="98"
              placeholder="请输入"
              v-model="receiptForm.remarks"/>
          </el-form-item>
        </div>

      </el-form>
      <span
        slot="footer"
        class="dialog-footer">
        <el-button @click="handleClose">
          <i class="el-icon-circle-close" />
          取 消
        </el-button>
        <el-button
          type="primary"
          @click="toSaveReceipt()">
          <i class="el-icon-circle-check" />
          确 定
        </el-button>
      </span>
    </el-dialog>
    <invoice-details
      :display-or-not="displayOrNotDetails"
      :invoice-url="activeInvoiceUrl"
      :busness-type="1"
      :invoice-no="activeInvoiceNo"
      @cancelDialog="cancelDialog" />
  </div>
</template>

<script>
import {
  statusArr,
  collectionColumns,
  invoiceColumns,
  nissinReadColunmns
  // collectionDetailsColunmns,
  // collectionDetailsListColunmns
} from './const'
import Pagination from '@components/custom-pagination'
import RecordInfo from '@/moduleComponents/beforeSettle/distributorSide/purchasingManagement/record'
import {
  distributorInvoiceById,
  quaryTradeReceiptDetail,
  quaryPssReceiptListInfo,
  insertTradeReceiptHistory
} from '@const/beforeSettleApi'
import ElEditable from '@components/el-editable'
import InvoiceDetails from '@/moduleComponents/beforeSettle/invoiceDetails'
import { cloneDeep, isObject, hasIn } from 'lodash'
import { formatPrice } from '@const/agencySaas'
import { getFormatterPrice, formatDate } from '@const/filter'
export default {
  components: { ElEditable, Pagination, RecordInfo, InvoiceDetails },
  data () {
    return {
      imageicon: require('@assets/icon/beforeSettle/imageicon.png'),
      // 查看发票详情
      displayOrNotDetails: false,
      activeInvoiceUrl: '',
      activeInvoiceNo: '',
      id: this.$route.query.id,
      orderStatus: null,
      // 表格Loading
      tableLoading: false,

      // 收款记录数据
      collectionList: [],
      collectionColumns,
      // 收款记录数据
      invoiceList: [],
      invoiceColumns,
      not: false,
      // 订单基本信息
      headerInfo: {},
      nissinReadColunmns,
      // 发票影像信息
      nissinVisble: false,
      receiptForm: {
        tradeAmount: '',
        remarks: ''
      }
    }
  },
  computed: {
    surplusMoney () {
      let num = null
      if (this.collectionList.length !== 0) {
        num = this.collectionList[0].surplusAmount
      } else {
        num = this.headerInfo.totalAmount || null
      }
      return num
    }
  },
  mounted () {
    this.getBaseInfo()
    if (Number(this.$route.query.status) === 1 || Number(this.$route.query.status) === 4) {
      let arr = [{ type: 'primary', val: '收款', handle: this.toReceipt }]
      const btn = {
        type: 'btn',
        arr
      }
      this.$store.commit('changeLayoutHandle', btn)
    }
  },
  methods: {
    getFormatterPrice,
    formatPrice,
    select (sel, row) {
      if (this.not) { return }
      this.not = true
      this.filterArr = this.invoiceList.filter(item => item.id === row.id && item !== row)
      this.filterArr.forEach(i => {
        this.$refs.table.$refs.table.toggleRowSelection(i)
      })
      this.not = false
    },
    // 查看发票详情
    toLookDetailsList (data) {
      // 跳转地址-应收单详情
      this.$router.push({
        path: '/distributorSide/salesManagement/common/invoiceDetails',
        query: {
          id: data.receiptPayId,
          invoiceNo: data.invoiceNo
        }
      })
    },
    // 查看发票详情
    toLookDetails (val) {
      this.activeInvoiceUrl = val.invoiceUrl
      this.activeInvoiceNo = val.invoiceNo
      this.displayOrNotDetails = true
    },
    cancelDialog () {
      this.activeInvoiceUrl = ''
      this.activeInvoiceNo = ''
      this.displayOrNotDetails = false
      this.getBaseInfo()
    },
    getBaseInfo () {
      const body = {
        tradeId: this.id
      }
      this.$axios.$post(quaryTradeReceiptDetail, body)
        .then(data => {
          // const baseInfo = hasIn(data, 'payload.orderStatus') ? data.payload : {}
          const baseInfo = data.payload || {}
          this.collectionList = baseInfo.tradeHistory || []// 收款详情
          this.invoiceList = baseInfo.invoiceList || []// 收款详情
          // 设计金额的转成三位小数
          if (baseInfo.invoiceAmount) {
            baseInfo.totalAmount = baseInfo.invoiceAmount
            baseInfo.invoiceAmount = baseInfo.invoiceAmount.toFixed(3) || 0
          }
          if (baseInfo.prodTotalAmount) {
            baseInfo.prodTotalAmount = getFormatterPrice(baseInfo.prodTotalAmount)
          }

          // -----我不知道这个有啥用。、----
          // baseInfo.receiptPayDetail.forEach(item => {
          //   if (item.invoiceAmountTax) {
          //     item.invoiceAmountTax = getFormatterPrice(item.invoiceAmountTax)
          //   }
          // })
          // -----------------------------

          // Object.keys(baseInfo).forEach(key => {
          //   if (key === 'orderStatus') {
          //     this.orderStatus = baseInfo[key]
          //     baseInfo[key] = statusArr[baseInfo[key]]
          //   }
          //   this.$set(this.headerInfo, key, baseInfo[key] || '--')
          // })
          this.headerInfo = baseInfo
        })
    },
    // 收款框
    toReceipt () {
      if (!this.collectionList[0] || Number(this.collectionList[0].surplusAmount) > 0) {
        this.nissinVisble = true
      } else if (this.collectionList[0].surplusAmount === 0) {
        this.$message.warning('收款已完成不可重复操作！')
      }
    },
    // 关闭弹框
    handleClose () {
      this.nissinVisble = false
      this.receiptForm = {
        tradeAmount: '',
        remarks: ''
      }
    },
    // 更新收款
    toSaveReceipt () {
      let num = this.collectionList.length ? this.collectionList[0].surplusAmount : this.headerInfo.invoiceAmount
      if (this.receiptForm.tradeAmount > Number(num)) {
        this.$message.warning('本次收款金额不能大于剩余收款金额！')
        return
      }
      if (!this.receiptForm.tradeAmount) {
        this.$message.warning('请输入本次收款金额！')
        return
      }
      let data = {
        ...this.receiptForm,
        tradeId: this.id
      }
      this.$axios.$post(insertTradeReceiptHistory, data).then(res => {
        if (res.code === '0') {
          this.$message.success('收款成功')
          this.handleClose()
          this.getBaseInfo()
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
@import '../m-front-common/pc/assets/var.less';
.invoice-list-box {
  background: @bgColor;
  height: 100%;
  position: absolute;
  overflow: auto;
  .common-ui {
    background: #fff;
    margin-bottom: 8px;
  }
}
</style>
